<template>
  <div class="department-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>部门列表</span>
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </div>
      </template>
      <el-table :data="departmentData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="部门名称" />
        <el-table-column prop="master" label="负责人" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="departmentFormRef"
        :model="departmentForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="负责人" prop="master">
          <el-input v-model="departmentForm.master" placeholder="请输入负责人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const departmentData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const departmentFormRef = ref(null)

// 表单数据
const departmentForm = reactive({
  id: '',
  name: '',
  master: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  master: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取部门列表
const getDepartmentList = () => {
  loading.value = true
  axios({
    url: '/api/sysdept/sysDept/showAll',
    method: 'get'
  }).then((res) => {
    if (res.data.code === 200) {
      departmentData.value = res.data.data
    } else {
      ElMessage.error(res.data.msg || '获取部门列表失败')
    }
  }).catch((error) => {
    ElMessage.error('获取部门列表失败')
    console.error(error)
  }).finally(() => {
    loading.value = false
  })
}

// 重置表单
const resetForm = () => {
  if (departmentFormRef.value) {
    departmentFormRef.value.resetFields()
  }
  Object.assign(departmentForm, {
    id: '',
    name: '',
    master: ''
  })
}

// 新增部门
const handleAdd = () => {
  dialogTitle.value = '新增部门'
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  dialogTitle.value = '编辑部门'
  Object.assign(departmentForm, row)
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除部门"${row.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: `/api/sysdept/sysDept/deleteById/${row.id}`,
      method: 'delete'
    }).then((res) => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getDepartmentList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    }).catch((error) => {
      ElMessage.error('删除失败')
      console.error(error)
    })
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  if (!departmentFormRef.value) return
  
  departmentFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const isEdit = !!departmentForm.id
      const url = isEdit 
        ? `/api/sysdept/sysDept/update/${departmentForm.id}`
        : '/api/sysdept/sysDept/add'
      const method = isEdit ? 'put' : 'post'

      axios({
        url,
        method,
        data: departmentForm
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(isEdit ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getDepartmentList()
        } else {
          ElMessage.error(res.data.msg || (isEdit ? '修改失败' : '添加失败'))
        }
      }).catch((error) => {
        ElMessage.error(isEdit ? '修改失败' : '添加失败')
        console.error(error)
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

onMounted(() => {
  getDepartmentList()
})
</script>

<style lang="scss" scoped>
.department-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 